//
//  MasterViewController.m
//  WorkManager
//
//  Created by iD Student on 7/17/12.
//  Copyright (c) 2012 iD Student. All rights reserved.
//

#import "MasterViewController.h"

@implementation MasterViewController

@synthesize appointmentStore;

//Deallocate the view controller
- (void)dealloc
{
    [super dealloc];
}

//Run un the data methods for initializing the view
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [AppDel setMvc:self];
    
	// Do any additional setup after loading the view, typically from a nib.
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlackOpaque];
    self.navigationItem.leftBarButtonItem = self.editButtonItem;

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)];
    self.navigationItem.rightBarButtonItem = addButton;
    [addButton release];
    addButton = nil;
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *data = [defaults objectForKey:@"data"];
    self.appointmentStore = (AppointmentStore *)[NSKeyedUnarchiver unarchiveObjectWithData:data];
    
    if(self.appointmentStore==NULL)
        self.appointmentStore = [[AppointmentStore alloc] init];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.appointmentStore sortAppointments];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)insertNewObject:(id)sender
{
    [self.appointmentStore createAppointmentReport];
    [self.tableView reloadData];
    [self performSegueWithIdentifier:@"showDetail" sender:sender];
}

#pragma mark - Table View

//Return the number of sections in the table view
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//Return the number of rows in the table view
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //Return the number of appointment reports in the array in the store
    return [[self.appointmentStore allAppointmentReports] count];
}

//Return a cell to be displayed in the table view
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell==nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    //Get the DATE as a string from the appointmentReport
    //Create the calendar in which to place the date
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    //Create the time components to store the components of now
    NSDateComponents *dateComponents = [gregorian components:(NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit| NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[[[self.appointmentStore allAppointmentReports] objectAtIndex:[indexPath row]] date]];
    
    //Create a string for the date
    NSString *dateString = [NSString stringWithFormat:@"%d/%d/%d", [dateComponents month] , [dateComponents day], [dateComponents year]];

    
    //Set the cell label to be the name of the appointment it's representing
    cell.textLabel.text = [[[self.appointmentStore allAppointmentReports] objectAtIndex:[indexPath row]] name];
    
    //Set the detail text to be the date string
    cell.detailTextLabel.text = dateString;
    
    [gregorian release];
    gregorian = nil;
    
    [CellIdentifier release];
    CellIdentifier = nil;
    
    return cell;
}

//Allow the tableview to edit all rows
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.appointmentStore removeAppointmentReportAtIndex:[indexPath row]];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        [[segue destinationViewController] setAppointmentReport:[[self.appointmentStore allAppointmentReports] objectAtIndex:[indexPath row]]];
    }
}

@end
